package hc.bre.call

import static org.junit.jupiter.api.Assertions.*

import org.junit.jupiter.api.Test

import hc.bre.call.SqlQueryDefinition
import hc.bre.call.SqlQueryItem
import hc.bre.runner.ScriptLoaderRunner

@groovy.transform.CompileStatic
class SqlQueryTest {
	@Test
	void constructor() {
		SqlQueryItem sqi = new SqlQueryItem();
		SqlQueryDefinition ruleDef = new SqlQueryDefinition();
	}

	String jsonText ='''
{
  "rid" : 264,
  "rtype" : "rule:call:sqlquery",
  "rname" : "UserInfo",
  "rpath" : "xsxdjc/UserInfo",
  "rversion" : 0,
  "rtdata" : null,
  "rmemo" : "",
  "rtest" : "{}",
  "rmaxid" : 1,
  "dataSource" : 0,
  "beforeQuery" : "",
  "afterQuery" : "",
  "list" : [{"id":1,"code":"SQL","name":"SQL","content":"select * from user"}]
}
'''

	@Test
	void load() {
		SqlQueryDefinition ruleDef = (SqlQueryDefinition) new SqlQueryDefinition().load(jsonText);
		assert ruleDef.list[0].code =='SQL'
	}

	@Test
	void buildScript() {
		SqlQueryDefinition ruleDef = (SqlQueryDefinition) new SqlQueryDefinition().load(jsonText);
		SqlQueryBuilder builder = new SqlQueryBuilder() {
					@Override
					public String _dataSource() {
						return 'null';
					}
				};

		ScriptLoaderRunner runner = ScriptLoaderRunner.forRule(ruleDef,builder);

		assertNotNull runner.buildRuleClass()

		//println runner.ruleClassScript;
	}

	@Test
	void buildAndRun() {
		
		hc.bre.DBTest.initIfNone()
		
		SqlQueryDefinition ruleDef = (SqlQueryDefinition) new SqlQueryDefinition().load(jsonText);
		SqlQueryBuilder builder = new SqlQueryBuilder() {
					@Override
					public String _dataSource() {
						'''{
			org.springframework.jdbc.datasource.DriverManagerDataSource dataSource = new org.springframework.jdbc.datasource.DriverManagerDataSource();
			dataSource.driverClassName = 'org.h2.Driver';
			dataSource.url = 'jdbc:h2:mem:testdb;MODE=MYSQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE';
			dataSource.username = 'root';
			dataSource.password = 'root';
			return dataSource;
		}.call()''';
					}
				};

		ScriptLoaderRunner runner = ScriptLoaderRunner.forRule(ruleDef,builder);

		def ret = runner.run(null);
		println hc.Util.jsonWrite(ret);
	}
}
